home *** CD-ROM | disk | FTP | other *** search
- Path: ix.netcom.com!netnews
- From: miker3@ix.netcom.com (Mike Rubenstein)
- Newsgroups: comp.lang.c++
- Subject: Re: should operator== and operator= be virtual?
- Date: Tue, 30 Jan 1996 12:30:02 GMT
- Organization: Netcom
- Message-ID: <310e0cf6.52459584@nntp.ix.netcom.com>
- References: <4ejvkr$btb@itnews.sc.intel.com>
- NNTP-Posting-Host: ix-dc8-20.ix.netcom.com
- X-NETCOM-Date: Tue Jan 30 4:30:17 AM PST 1996
- X-Newsreader: Forte Agent .99c/16.141
-
- etse@scdt.intel.com (Eric Tse) wrote:
-
- > Hi,
- >
- > Should operator==() and operator=() of a class be virtual if the class is
- > planned for extensibility? Personally I think in general assignement
- > operators should be non-virtual, but I am not sure about equality operator.
- > Could anyone helps? Thanks.
- >
- > class A {
- > public:
- > A& operator=(const A&);
- > virtual bool operator==(const A&) const;
- > virtual bool operator!=(const A&) const;
- > };
- >
- > class B : public A {
- > public:
- > B& operator=(const B&);
- >
- > virtual bool operator==(const A&) const; // ?
- > virtual bool operator!=(const A&) const; // ?
- >
- > virtual bool operator==(const B&) const; // ?
- > virtual bool operator!=(const B&) const; // ?
- > };
-
- Why do you think assignment operators should be non-virtual? Any
- function that a derived class may want to override should usually be
- made virtual.
-
- operator= is a special case. Even if there is no explicit override of
- operator=, it is not inheritted. If a class does not provide
- operator=, a default one will be generated that does a memberwise
- copy. So, even if the derived classes never explicitly override
- operator=, you probably need to make it virtual if any derived classes
- may add data members.
-
- Example:
-
- class A {
- public:
- A& operator=(const A&);
- };
-
- class B : public A {
- private:
- int i;
- };
-
- A* a = new B;
- B b;
- (*a) = b;
-
- This will not work right; A::operator= will be called and B::i will
- not be copied.
-
- operator== should be virtual if a derived class may want to override
- it. I'd guess that usually this means it should be virtual (read: in
- my programs I almost always want it virtual), but there probably are
- examples where it makes no sense to override it.
-
-
- Michael M Rubenstein
-